package com.cyan.app.workflow.activity.WHM;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.Invbat2LabBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshListView;
import com.google.gson.Gson;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * Created by DXW on 2017/10/30.
 */

public class CkDbNewActivity extends BaseActivity {
    private PullToRefreshListView mPullToRefreshExpandableListView;
    private PullToRefreshListView mPullToRefreshNoDataListView;
    private ListView mPoolShowListView;
    private CkDbAdapter adapter;
    public static HashMap<String, Invbat2LabBean.Invbat2Bean> selectedMap = new HashMap<String, Invbat2LabBean.Invbat2Bean>();
    private String fixnr;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private List<Invbat2LabBean.Invbat2Bean> mInvbat2BeanList = new ArrayList<Invbat2LabBean.Invbat2Bean>();
    private CheckBox mCheckBoxAll;
    private String key = "";
    private Button mButtonSelect;
    private View mFooter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whm_ck_db);
        titleBar();
        initView();
        startActivityForResult(new Intent(CkDbNewActivity.this, CaptureActivity.class), 0x0001);
       // AsyncLoader task = new AsyncLoader();
       // task.execute("30701", "A");
        selectedMap.clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x0001 && resultCode == RESULT_OK) {
            String result = "";
            if (data == null) {
                return;
            }
            result = data.getStringExtra("result");
            fixnr = String.valueOf(result);
            if (!fixnr.contains("30010")) {
                AppUtils.showTip(CkDbNewActivity.this, "请扫描库位条码。");
                return;
            }
            fixnr = fixnr.substring(5);
            AsyncLoader task = new AsyncLoader();
            task.execute(HttpConfig.HTTP_MAIN_SERVER_ACTION_30701, fixnr);
        }
    }

    private void titleBar() {
        TextView mTitleName = (TextView) findViewById(R.id.top_title_info);
        mTitleName.setText("选择调出明细");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        Button mTitleSeach = (Button) findViewById(R.id.top_title_refres);
        mTitleSeach.setVisibility(View.GONE);
        mTitleSeach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedMap.values().size() <= 0) {
                    AppUtils.showTip(CkDbNewActivity.this, "请选择记录");
                    return;
                }
                List<Invbat2LabBean.Invbat2Bean> resultList = new ArrayList<Invbat2LabBean.Invbat2Bean>();
                Invbat2LabBean result = new Invbat2LabBean();
                for (Invbat2LabBean.Invbat2Bean bean : selectedMap.values()) {
                    if (bean.getOnhand2() <=0) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "调拨出数量必须大于0");
                        return;
                    }
                    if (bean.getOnhand2() > bean.getOnhand1()) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "调拨数量不能大于库存数量");
                        return;
                    }
                    if (bean.getVarnr1().isEmpty() || bean.getVarnr1().trim().length() == 0) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "调拨批次不能为空");
                        return;
                    }
                    if (bean.getVarnr1().length() > 18) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getVarnr1() + "调拨入批次不能大于18个字符");
                        return;
                    }
                    if (isExistedInList(bean)) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "不能重复添加");
                        return;
                    }
                    resultList.add(bean);
                }
                result.setResult(resultList);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("ck_db_new", result);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                selectedMap.clear();
                finish();
            }
        });
    }

    private void initView() {
        mFooter = (View) findViewById(R.id.whm_ck_db_foot);
        mFooter.setVisibility(View.GONE);
        mPullToRefreshNoDataListView = (PullToRefreshListView) findViewById(R.id.no_match_show);
        mPullToRefreshNoDataListView.setVisibility(View.GONE);
        ListView listView = mPullToRefreshNoDataListView.getRefreshableView();
        listView.setAdapter(mNoDataAdapter);

        mPullToRefreshExpandableListView = (PullToRefreshListView) findViewById(R.id.show_list);
        mPoolShowListView = mPullToRefreshExpandableListView.getRefreshableView();
        adapter = new CkDbAdapter(this);
        mPoolShowListView.setAdapter(adapter);
        mPullToRefreshNoDataListView.setPullToRefreshEnabled(false);
        mPullToRefreshExpandableListView.setPullToRefreshEnabled(false);

        Button btnDelete = (Button) findViewById(R.id.whm_ck_db_btn_delete);
        btnDelete.setVisibility(View.GONE);
        Button btnDb = (Button) findViewById(R.id.whm_ck_db_btn_db);
        btnDb.setVisibility(View.GONE);
        mButtonSelect = (Button) findViewById(R.id.whm_ck_db_btn_select);
        mButtonSelect.setVisibility(View.VISIBLE);
        mButtonSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectedMap.values().size() <= 0) {
                    AppUtils.showTip(CkDbNewActivity.this, "请选择记录");
                    return;
                }
                List<Invbat2LabBean.Invbat2Bean> resultList = new ArrayList<Invbat2LabBean.Invbat2Bean>();
                Invbat2LabBean result = new Invbat2LabBean();
                for (Invbat2LabBean.Invbat2Bean bean : selectedMap.values()) {
                    if (bean.getOnhand2() <=0) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "调拨出数量必须大于0");
                        return;
                    }
                    if (bean.getOnhand2() > bean.getOnhand1()) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "调拨数量不能大于库存数量");
                        return;
                    }
                    if (bean.getVarnr1().isEmpty() || bean.getVarnr1().trim().length() == 0) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "调拨批次不能为空");
                        return;
                    }
                    if (bean.getVarnr1().length() > 18) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getVarnr1() + "调拨入批次不能大于18个字符");
                        return;
                    }
                    if (isExistedInList(bean)) {
                        AppUtils.showTip(CkDbNewActivity.this, bean.getItnbr() + "不能重复添加");
                        return;
                    }
                    resultList.add(bean);
                }
                result.setResult(resultList);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("ck_db_new", result);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                selectedMap.clear();
                finish();
            }
        });

        mCheckBoxAll = (CheckBox) findViewById(R.id.whm_ck_db_selected);
        mCheckBoxAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    selectedMap.clear();
                    for (int i = 0; i < mInvbat2BeanList.size(); i++) {
                        key = mInvbat2BeanList.get(i).getWareh() + "_" +mInvbat2BeanList.get(i).getFixnr() + "_" + mInvbat2BeanList.get(i).getItnbr() + "_" + mInvbat2BeanList.get(i).getVarnr();
                        selectedMap.put(key, mInvbat2BeanList.get(i));
                    }
                } else {
                    selectedMap.clear();
                }
                mPoolShowListView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                mCheckBoxAll.setSelected(!mCheckBoxAll.isSelected());
                refreshSelectedCount();
            }
        });
        View itnbr_bat_selected_line = findViewById(R.id.whm_ck_db_selected_line);
        itnbr_bat_selected_line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCheckBoxAll.setChecked(!mCheckBoxAll.isChecked());
            }
        });
    }

    private BaseAdapter mNoDataAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView != null) {
                return convertView;
            }
            convertView = LayoutInflater.from(CkDbNewActivity.this).inflate(R.layout.layout_main_nodata, null);
            return convertView;
        }
    };

    private class CkDbAdapter extends BaseAdapter {
        private LayoutInflater inflater = null;

        public CkDbAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return mInvbat2BeanList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            holder = new ViewHolder();
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_VERTICAL;
            convertView = inflater.inflate(R.layout.whm_ck_db_list, null);
            holder.itnbr_bat_fixnr = (TextView) convertView.findViewById(R.id.whm_ck_dblist_fixnr);
            holder.itnbr_bat_fixnr.setText(mInvbat2BeanList.get(position).getFixnr());

            holder.itnbr_bat_wareh = (TextView) convertView.findViewById(R.id.whm_ck_dblist_wareh);
            holder.itnbr_bat_wareh.setText(mInvbat2BeanList.get(position).getWareh());

            holder.itnbr_bat_itnbr = (TextView) convertView.findViewById(R.id.whm_ck_dblist_itnbr);
            holder.itnbr_bat_itnbr.setText(mInvbat2BeanList.get(position).getItnbr());

            holder.itnbr_bat_itdsc = (TextView) convertView.findViewById(R.id.whm_ck_dblist_itdsc);
            holder.itnbr_bat_itdsc.setText(mInvbat2BeanList.get(position).getItdsc());

            holder.itnbr_bat_onhand1 = (TextView) convertView.findViewById(R.id.whm_ck_dblist_onhand1);
            holder.itnbr_bat_onhand1.setText(mInvbat2BeanList.get(position).getOnhand1().toString());

            holder.itnbr_bat_onhand2 = (EditText) convertView.findViewById(R.id.whm_ck_dblist_onhand1_new);
            holder.itnbr_bat_onhand2.setText(mInvbat2BeanList.get(position).getOnhand2().toString());

            holder.itnbr_bat_varnr = (TextView) convertView.findViewById(R.id.whm_ck_dblist_varnr);
            holder.itnbr_bat_varnr.setText(mInvbat2BeanList.get(position).getVarnr());

            holder.itnbr_bat_varnr1 = (EditText) convertView.findViewById(R.id.whm_ck_dblist_varnr1);
            holder.itnbr_bat_varnr1.setText(mInvbat2BeanList.get(position).getVarnr1());
            holder.itnbr_bat_selected = (CheckBox) convertView.findViewById(R.id.whm_ck_dblist_selected);
            final int pos = position;
            key = mInvbat2BeanList.get(position).getWareh() + "_" +mInvbat2BeanList.get(position).getFixnr() + "_" + mInvbat2BeanList.get(position).getItnbr() + "_" + mInvbat2BeanList.get(position).getVarnr();
            holder.itnbr_bat_selected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    key = mInvbat2BeanList.get(position).getWareh() + "_" +mInvbat2BeanList.get(position).getFixnr() + "_" + mInvbat2BeanList.get(position).getItnbr() + "_" + mInvbat2BeanList.get(position).getVarnr();
                    if (isChecked) {
                        if (!selectedMap.containsKey(key)) {
                            selectedMap.put(key, mInvbat2BeanList.get(position));
                        }
                    } else {
                        if (selectedMap.containsKey(key)) {
                            selectedMap.remove(key);
                        }
                    }
                    holder.itnbr_bat_selected.setSelected(selectedMap.containsKey(key));
                    refreshSelectedCount();
                }
            });

            holder.itnbr_bat_selected.setChecked(selectedMap.containsKey(key));
            holder.itnbr_bat_onhand2.addTextChangedListener(new TextWatcher() {
                Double num = 0.00;

                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (!editable.toString().isEmpty()) {
                        num = Double.parseDouble(editable.toString());
                        mInvbat2BeanList.get(position).setOnhand2(num);
                    }else {
                        mInvbat2BeanList.get(position).setOnhand2(num);
                    }
                }
            });
            holder.itnbr_bat_varnr1.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (!editable.toString().isEmpty()) {
                        mInvbat2BeanList.get(position).setVarnr1(editable.toString());
                    }else {
                        mInvbat2BeanList.get(position).setVarnr1("");
                    }
                }
            });
            holder.itnbr_bat_selected_line = convertView.findViewById(R.id.whm_ck_dblist_left_layout);
            holder.itnbr_bat_selected_line.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    holder.itnbr_bat_selected.setChecked(!holder.itnbr_bat_selected.isChecked());
                }
            });
            convertView.setTag(holder);
            return convertView;
        }

        class ViewHolder {
            CheckBox itnbr_bat_selected;
            TextView itnbr_bat_itnbr;
            TextView itnbr_bat_itdsc;
            TextView itnbr_bat_onhand1;
            EditText itnbr_bat_onhand2;
            TextView itnbr_bat_fixnr;
            TextView itnbr_bat_wareh;
            TextView itnbr_bat_varnr;
            EditText itnbr_bat_varnr1;
            View itnbr_bat_selected_line;
        }
    }

    public class AsyncLoader extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            showdialog.showDialog(CkDbNewActivity.this);
        }
        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try {
                JSONObject param = new JSONObject();
                param.put("Fixnr", params[1]);
                result = GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            } catch (Exception e) {
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null || s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            Invbat2LabBean commonBean = new Gson().fromJson(s, Invbat2LabBean.class);
            if (commonBean.getCode() < 1) {
                AppUtils.showTip(CkDbNewActivity.this, commonBean.getMsg());
            } else {
                mInvbat2BeanList = commonBean.getResult();
                for (Invbat2LabBean.Invbat2Bean bean:mInvbat2BeanList){
                    bean.setOnhand2(bean.getOnhand1());
                    bean.setVarnr1(bean.getVarnr());
                }
                refreshPoolListView(mInvbat2BeanList);
            }
            showdialog.closeDialog();
        }
    }

    private void refreshPoolListView(List<Invbat2LabBean.Invbat2Bean> list) {
        if (list == null) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }
        if (list.size() == 0) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }
        mPullToRefreshNoDataListView.setVisibility(View.GONE);
        mPullToRefreshExpandableListView.setVisibility(View.VISIBLE);

        CkDbAdapter adapter = new CkDbAdapter(this);
        mPoolShowListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    //判断列表里是否已存在
    private boolean isExistedInList(Invbat2LabBean.Invbat2Bean item) {
        for (Invbat2LabBean.Invbat2Bean bean : CkDbActivity.mInvbat2BeanList) {
            if (item.getFixnr().equals(bean.getFixnr()) && item.getItnbr().equals(bean.getItnbr()) && item.getVarnr().equals(bean.getVarnr())) {
                return true;
            }
        }
        return false;
    }
    //统计选择记录数
    private void refreshSelectedCount() {
        mButtonSelect.setText("选择(" + selectedMap.size() + ")");
        if(selectedMap.size()>0&&mFooter.getVisibility()==View.GONE){
            mFooter.setVisibility(View.VISIBLE);
        }
        if(selectedMap.size()==0){
            mFooter.setVisibility(View.GONE);
        }
    }
}
